<template>
  <view class="navigation-container">
    <!-- 地图区域 -->
    <view class="map-container">
      <map
        id="navigationMap"
        :latitude="mapCenter.latitude"
        :longitude="mapCenter.longitude"
        :scale="mapScale"
        :markers="mapMarkers"
        :polyline="polylines"
        :show-location="true"
        :enable-3D="true"
        :show-compass="true"
        :enable-overlooking="true"
        :enable-zoom="true"
        :enable-scroll="true"
        :enable-rotate="true"
        @updated="onMapUpdated"
        @tap="onMapTap"
        @markertap="onMarkerTap"
        @markerclick="onMarkerClick"
        class="navigation-map"
      >
      </map>
      
      <!-- 地图加载状态 -->
      <view v-if="!mapLoaded" class="map-loading">
        <view class="loading-spinner"></view>
        <text class="loading-text">地图加载中...</text>
      </view>
      
      <!-- 定位加载状态 -->
      <view v-if="isLocationLoading" class="location-loading">
        <view class="loading-spinner"></view>
        <text class="loading-text">正在定位...</text>
      </view>
    </view>
    
    <!-- 目的地信息卡片 -->
    <view v-if="destination" class="destination-card">
      <view class="destination-info">
        <view class="destination-name">{{ destination.name }}</view>
        <view class="destination-address">{{ destination.address }}</view>
      </view>
      <view class="destination-actions">
        <button class="nav-button" @click="startNavigation">导航</button>
      </view>
    </view>
    
 
  </view>
</template>

<script>
export default {
  data() {
    return {
      mapCenter: {
        latitude: 35.2394,
        longitude: 113.2331
      },
      mapScale: 15,
      mapMarkers: [],
      polylines: [],
      mapLoaded: false,
      userLocation: null,
      destination: null,
      isLocationLoading: false,
      isNavigating: false,
      navigationDistance: '0.0',
      navigationTime: '0',
      currentRoute: null
    }
  },
  
  onLoad(options) {
    console.log('导航页面加载，参数：', options);
    
    // 获取目的地信息
    if (options.stationId) {
      this.destination = {
        id: options.stationId,
        name: decodeURIComponent(options.name || '目的地'),
        address: decodeURIComponent(options.address || ''),
        latitude: parseFloat(options.latitude) || 35.2394,
        longitude: parseFloat(options.longitude) || 113.2331
      };
    }
    
    this.initNavigation();
  },
  
  methods: {
     // 初始化导航
     initNavigation() {
       this.getUserLocation();
       // 不自动规划路线，等用户点击导航按钮
     },
    
    // 获取用户位置
    async getUserLocation() {
      this.isLocationLoading = true;
      
      try {
        uni.showLoading({
          title: '定位中...'
        });
        
        const location = await this.getCurrentLocation();
        if (location.success) {
          this.userLocation = {
            latitude: location.latitude,
            longitude: location.longitude
          };
          this.mapCenter = {
            latitude: location.latitude,
            longitude: location.longitude
          };
           this.mapScale = 15;
           
           this.initMapMarkers();
           // 不自动规划路线，等用户点击导航按钮
          
          uni.showToast({
            title: '定位成功',
            icon: 'success',
            duration: 1500
          });
        } else {
          // 定位失败，使用默认位置
          this.userLocation = {
            latitude: 35.2159,
            longitude: 113.2418
          };
          this.mapCenter = {
            latitude: 35.2159,
            longitude: 113.2418
          };
          
          this.initMapMarkers();
          // 不自动规划路线，等用户点击导航按钮
          
          uni.showToast({
            title: '定位失败，使用默认位置',
            icon: 'none',
            duration: 2000
          });
        }
      } catch (error) {
        console.error('获取位置失败：', error);
        // 使用默认位置
        this.userLocation = {
          latitude: 35.2159,
          longitude: 113.2418
        };
        this.mapCenter = {
          latitude: 35.2159,
          longitude: 113.2418
        };
        
        this.initMapMarkers();
        // 不自动规划路线，等用户点击导航按钮
        
        uni.showToast({
          title: '定位失败，使用默认位置',
          icon: 'none',
          duration: 2000
        });
      } finally {
        this.isLocationLoading = false;
        uni.hideLoading();
      }
    },
    
    // 获取当前位置（参考车辆维修模块实现）
    getCurrentLocation() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          altitude: false,
          geocode: true,
          success: (res) => {
            console.log('定位成功:', res);
            resolve({
              success: true,
              latitude: res.latitude,
              longitude: res.longitude,
              address: res.address || '未知地址'
            });
          },
          fail: (err) => {
            console.log('获取位置失败:', err);
            // 定位失败时返回默认位置（焦作市）
            resolve({
              success: false,
              latitude: 35.2159,
              longitude: 113.2418,
              address: '焦作市',
              error: err.errMsg || '获取位置失败'
            });
          }
        });
      });
    },
    
    // 初始化地图标记
    initMapMarkers() {
      const markers = [];
      
      // 用户位置标记
      if (this.userLocation) {
        markers.push({
          id: 'user',
          latitude: this.userLocation.latitude,
          longitude: this.userLocation.longitude,
          width: 25,
          height: 25,
          anchor: {
            x: 0.5,
            y: 0.5
          },
          iconPath: '/static/static-lj/椭圆 3 拷贝 2.png',
          callout: {
            content: '我的位置',
            color: '#fff',
            fontSize: 14,
            bgColor: '#0a78ff',
            padding: 10,
            borderRadius: 5,
            textAlign: 'center'
          }
        });
      }
      
      // 目的地标记
      if (this.destination) {
        markers.push({
          id: 'destination',
          latitude: this.destination.latitude,
          longitude: this.destination.longitude,
          width: 30,
          height: 30,
          anchor: {
            x: 0.5,
            y: 1
          },
          iconPath: '/static/static-lj/位置 拷贝 4.png',
          callout: {
            content: this.destination.name,
            color: '#fff',
            fontSize: 14,
            bgColor: '#ff6a2f',
            padding: 10,
            borderRadius: 5,
            textAlign: 'center'
          }
        });
      }
      
      this.mapMarkers = markers;
      this.mapLoaded = true;
    },
    
    // 计算路线
    calculateRoute() {
      if (!this.userLocation || !this.destination) return;
      
      // 模拟路线计算
      const distance = this.calculateDistance(
        this.userLocation.latitude,
        this.userLocation.longitude,
        this.destination.latitude,
        this.destination.longitude
      );
      
      this.navigationDistance = distance.toFixed(1);
      this.navigationTime = Math.round(distance * 2); // 假设平均速度30km/h
      
      // 创建路线
      this.polylines = [{
        points: [
          {
            latitude: this.userLocation.latitude,
            longitude: this.userLocation.longitude
          },
          {
            latitude: this.destination.latitude,
            longitude: this.destination.longitude
          }
        ],
        color: '#0a78ff',
        width: 6,
        dottedLine: false
      }];
    },
    
    // 计算距离
    calculateDistance(lat1, lng1, lat2, lng2) {
      const R = 6371; // 地球半径（公里）
      const dLat = (lat2 - lat1) * Math.PI / 180;
      const dLng = (lng2 - lng1) * Math.PI / 180;
      const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
        Math.sin(dLng / 2) * Math.sin(dLng / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return R * c;
    },
    
    // 开始导航（参考车辆维修模块）
    startNavigation() {
      if (!this.userLocation || !this.destination) {
        uni.showToast({
          title: '位置信息不完整',
          icon: 'none'
        });
        return;
      }
      
      // 点击导航按钮后才规划路线
      this.calculateRoute();
      
      uni.showToast({
        title: '路线规划完成',
        icon: 'success'
      });
    },
    
    // 联系门店（参考车辆维修模块）
    callStation() {
      const phone = '400-123-4567'; // 默认电话
      uni.showModal({
        title: '联系门店',
        content: `是否拨打 ${phone}？`,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '成功拨打电话' + phone,
              icon: 'success'
            });
            uni.switchTab({
              url: '/pages/index/index'
            });
          }
        }
      });
    },
    
    // 地图事件处理
    onMapUpdated() {
      console.log('地图更新完成');
    },
    
    onMapTap(e) {
      console.log('地图点击：', e);
    },
    
    onMarkerTap(e) {
      console.log('标记点击：', e);
      const markerId = e.detail.markerId;
      if (markerId === 'destination') {
        // 点击目的地标记点，显示目的地信息
        uni.showToast({
          title: this.destination.name,
          icon: 'none'
        });
      }
    },
    
    onMarkerClick(e) {
      console.log('标记点击：', e);
    }
  }
}
</script>

<style scoped>
.navigation-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  position: relative;
}

/* 页面背景色区域 - 顶部蓝色区域 */
.navigation-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 350rpx; /* 蓝色区域高度 */
  background-color: #3184FD;
  z-index: 0; /* 在页面内容下方 */
}

.map-container {
  flex: 1;
  position: relative;
  margin: 20rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.navigation-map {
  width: 100%;
  height: 100%;
}

.map-loading,
.location-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #0a78ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.destination-card {
  background-color: #fff;
  margin: 0 20rpx 20rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.destination-info {
  flex: 1;
}

.destination-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.destination-address {
  font-size: 28rpx;
  color: #666;
}

.destination-actions {
  margin-left: 20rpx;
}

.nav-button {
  background-color: #0a78ff;
  color: #fff;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.nav-controls {
  background-color: #fff;
  margin: 0 20rpx 20rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.nav-info {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30rpx;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.nav-distance,
.nav-time {
  text-align: center;
}

.distance-value,
.time-value {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #0a78ff;
  line-height: 1;
}

.distance-unit,
.time-unit {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}

.nav-actions {
  display: flex;
  gap: 20rpx;
}

.control-btn {
  flex: 1;
  background-color: #f8f8f8;
  color: #333;
  border: 1rpx solid #ddd;
  border-radius: 50rpx;
  padding: 24rpx;
  font-size: 28rpx;
  text-align: center;
}

.control-btn:first-child {
  background-color: #0a78ff;
  color: #fff;
  border-color: #0a78ff;
}

.btn-text {
  font-weight: bold;
}
</style>